package com.tyqx.hashchainbiz.service.impl;

// import com.alibaba.fastjson.JSON;
import com.tyqx.hashchainbean.module.HashIndex;
import com.tyqx.hashchainbean.module.ProductOut;
import com.tyqx.hashchainbiz.service.ProductOutService;
import com.tyqx.hashchaindao.mapper.HashIndexMapper;
import com.tyqx.hashchaindao.mapper.ProductOutMapper;
import com.tyqx.hashchainutil.common.HashValueUtil;
import com.tyqx.hashchainutil.common.mongodb.ImagePathHashValueUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("productOutService")
public class ProductOutServiceImpl implements ProductOutService {

    @Resource
    private HashIndexMapper hashIndexMapper;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private ProductOutMapper productOutMapper;

    @Async
    public Integer productOut(ProductOut productOut) throws Exception{
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime=sdf.parse(sdf.format(currentDate));
        productOut.setCreateTime(createTime);
        productOut.setUpdateTime(createTime);
        String productOutStr= productOut.toString();


        String attachmentStr=productOut.getAttachment();
        if (!"".equals(attachmentStr) && attachmentStr != null) {
            String collectionName = "productOut";
            String imageHashValue = ImagePathHashValueUtil.insertAttachment(attachmentStr, mongoTemplate, collectionName);
            productOut.setAttachment(imageHashValue);
        }
        HashIndex hashIndex= HashValueUtil.getHashValue(productOutStr,mongoTemplate);
        Integer flag=hashIndexMapper.insert(hashIndex);

        productOut.setHashValue(hashIndex.getHashValue());
        return productOutMapper.addOutProduct(productOut);
    }

    @Override
    public List<ProductOut> getProductOutById(String donateId, String userName) {
        return productOutMapper.getProductOutById(donateId);
    }

    @Override
    public List<ProductOut> getProductOutByTime(Date startTime, Date endTime, String userName) {
        return productOutMapper.getProductOutByTime(startTime, endTime, userName);
    }
}
